package com.woniuxy.bookmallmanagersrever.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.bookmallmanagersrever.entity.TUrlPermission;
import com.woniuxy.bookmallmanagersrever.mapper.TUrlPermissionMapper;
import com.woniuxy.bookmallmanagersrever.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PermissionService {
    @Autowired
    TUrlPermissionMapper permissionMapper ;

    @Cacheable(value = "permission",key = "#root.targetClass+#root.methodName")
    public List<PermissionVo> findAllMenus() {

        return permissionMapper.selectAllMenus();
    }

    public PageInfo<TUrlPermission> findPermissionByPage(Integer now, Integer size, String name) {
        PageHelper.startPage(now,size);
        List<TUrlPermission> lists = permissionMapper.selectPermissionByName(name);
        return new PageInfo<>(lists);
    }

    @CacheEvict(value = "permission",allEntries = true)
    public void add(TUrlPermission permission) {
        permission.setInsertTime(new Date());
        permission.setUpdateTime(new Date());
        permissionMapper.insert(permission);
    }

    @CacheEvict(value = "permission",allEntries = true)
    public void modify(TUrlPermission permission) {
        permission.setUpdateTime(new Date());
        permissionMapper.updateByPrimaryKey(permission);
    }

    public List<TUrlPermission> findAllParentPermission() {
        return  permissionMapper.selectAllParentPermission();
    }

    @CacheEvict(value = "permission",allEntries = true)
    @Transactional
    public void removeByKey(int id) {
        //查询 所有 子菜单的id
        List<Integer> lists = permissionMapper.selectPerIdByParentId(id);
        if (lists != null && lists.size() >0){
            //先删除他的子菜单
            permissionMapper.deletePermissionByParentId(id);
            //删除子菜单  在 角色权限中间表中的数据
            permissionMapper.deleteAllChildPermissionInRole(lists);
        }
        //在删除 角色权限 中间表中的数据
        permissionMapper.deleteRoleAndPermissionByPermissionId(id);
        //在删除 权限数据
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Cacheable(value = "permission",key = "#root.targetClass+#root.methodName+#username")
    public List<PermissionVo> findMenusByManager(String username) {
        return permissionMapper.selectMenusByManager(username);
    }
}
